package com.beta.backend.gateway.filter;

import com.beta.backend.gateway.utils.ResponseUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @description  过滤器基础类，提供公共方法
 * @author: zdwang
 * @date 2021/12/2 19:20
 */
public abstract class AbstractGatewayFilter {

    protected ObjectMapper objectMapper;

    protected static final String BJWT = "bjwt";

    protected static final String USERID = "userId";

    protected static final String USER_INFO = "jwt-login-account";

    /**
     * 业务端类型
     */
    protected static final String END_TYPE_HEADER = "endType";

    /**
     * 渠道类型
     */
    protected static final String CHANNEL_HEADER = "channel";

    /**
     * 终端类型
     */
    protected static final String CLIENT_TYPE_HEADER = "clientType";

    protected static final String DEFAULT_CLIENT_TYPE = "MOBILE";

    protected static final String QIWEI_CHANNEL_VALUE = "QIWEI";

    protected static final String WEIXIN_CHANNEL_VALUE = "WEIXIN";



    protected Mono<Void> unauthorized(ServerWebExchange exchange) {
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        byte[] bytes = ResponseUtils.generateResponse(objectMapper, HttpStatus.UNAUTHORIZED)
                .getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
        return exchange.getResponse().writeWith(Flux.just(buffer));
    }

    protected Mono<Void> forbidden(ServerWebExchange exchange) {
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        byte[] bytes = ResponseUtils.generateResponse(objectMapper, HttpStatus.FORBIDDEN)
                .getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
        return exchange.getResponse().writeWith(Flux.just(buffer));
    }

    protected Mono<Void> methodNotAllowed(ServerWebExchange exchange) {
        exchange.getResponse().setStatusCode(HttpStatus.METHOD_NOT_ALLOWED);
        byte[] bytes = ResponseUtils.generateResponse(objectMapper, HttpStatus.METHOD_NOT_ALLOWED)
                .getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
        return exchange.getResponse().writeWith(Flux.just(buffer));
    }
}
